#include <rtdevice.h>
#include <rtthread.h>
#include <board.h>
#include "drv_soft_spi.h"
#include "dev_spi_flash_sfud.h"
#include <dfs_fs.h>

#define SSPI_BUS_NAME "sspi0"
#define SSPI_DEVICE_NAME "sspi00"
#define SSPI_FLASH_DEVICE_NAME "W25Q64S"

#define SPI_FLASH_CS_PIN    GET_PIN(B, 12)   // CS=PB12
int sspi_flash_init(void)
{
    /* 挂载SPI Flash设备到软SPI1总线 */
    if (rt_hw_softspi_device_attach(SSPI_BUS_NAME, SSPI_DEVICE_NAME, SPI_FLASH_CS_PIN) != RT_EOK)
    {
        rt_kprintf("Failed to attach SPI Flash!\n");
        return -RT_ERROR;
    }

    if (RT_NULL == rt_sfud_flash_probe(SSPI_FLASH_DEVICE_NAME, SSPI_DEVICE_NAME))
    {
        return -RT_ERROR;
    };

    #ifdef BSP_SOFT_SPI_FLASH_MOUNT_FATFS
    if (dfs_mount(SSPI_FLASH_DEVICE_NAME, "/spi", "elm", 0, 0) != 0)
    {
        LOG_W("mount to '/spi' failed! try to mkfs %s", SSPI_FLASH_DEVICE_NAME);
        dfs_mkfs("elm", SSPI_FLASH_DEVICE_NAME);
        if (dfs_mount(SSPI_FLASH_DEVICE_NAME, "/spi", "elm", 0, 0) == 0)
        {
            LOG_I("mount to '/spi' success!");
        }
    }
    LOG_I("mount to '/spi' success!");
    #endif

    return 0;
}
INIT_APP_EXPORT(sspi_flash_init);

void sspi_flash_test(void)
{
    struct rt_spi_device *spi_dev;
    rt_uint8_t write_buf[4] = {0x9F, 0x00, 0x00, 0x00}; // 读取ID命令
    rt_uint8_t read_buf[4] = {0};
    
    /* 获取SPI设备 */
    spi_dev = (struct rt_spi_device *)rt_device_find(SSPI_DEVICE_NAME);
    if (!spi_dev)
    {
        rt_kprintf("SPI device not found!\n");
        return;
    }

    /* 配置SPI模式 */
    struct rt_spi_configuration cfg;
    cfg.mode = RT_SPI_MODE_0 | RT_SPI_MSB; // 模式0, MSB first
    cfg.data_width = 8;
    cfg.max_hz = 1 * 1000 * 1000; // 1MHz
    rt_spi_configure(spi_dev, &cfg);

    /* 读取Flash ID */
    rt_spi_send_then_recv(spi_dev, write_buf, 1, read_buf, 3);
    
    rt_kprintf("Flash ID: 0x%02X%02X%02X\n", 
              read_buf[0], read_buf[1], read_buf[2]);
}

MSH_CMD_EXPORT(sspi_flash_test, sspi_flash_test!);